package com.fstec.ks.master.process;

import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.fstec.ks.master.MasterEngine;
import com.fstec.ks.master.bean.ServerInfoBean;
import com.sinotn.SinotnLogger;
import com.sinotn.SinotnRuntime;
import com.sinotn.error.MessageException;
import com.sinotn.task.DefaultProcessStatus;
import com.sinotn.util.StreamUtil;

/**
 * 异步构建授权接入文件
 * @Title AuthFileProcess.java
 * @Package com.fstec.ks.master.process
 * @Description 
 * Copyright: Copyright (c) 2023
 * Company:广东峰上科技有限公司
 * 
 * @author <a href="mailto:xieqj@fstec.com">谢启进</a>
 * @date 2023年10月10日 上午10:11:02
 * @version V1.0
 */
public class AuthFileProcess extends DefaultProcessStatus implements Runnable {
	@Autowired
	private MasterEngine masterEngine;
	private String ipAddr;
	private String path;
	public AuthFileProcess(String ipAddr){
		this.id=UUID.randomUUID().toString();
		this.ipAddr=ipAddr;
	}
	private int getRandomSalt(){
		return (127+RandomUtils.nextInt(128));
	}
	
	@Override
	public Map<String, Object> getExtInfo() {
		if(this.success && this.path!=null){
			HashMap<String, Object> info=new HashMap<String, Object>(1);
			info.put("path", path);
			return info;
		}
		return null;
	}
	@Override
	public void run() {
		FileOutputStream fos=null;
		try{
			File folder=new File(SinotnRuntime.getExamRuntimeFolder(), "Auth");
			if(!folder.exists()){
				folder.mkdirs();
			}
			this.message="正在构建授权文件";
			ServerInfoBean serverInfo=masterEngine.rebindIpAddr(this.ipAddr);
			this.message="正在写入授权文件";
			File file=new File(folder, "MasterAuth.dt");
			fos=new FileOutputStream(file);
			int randomKey=this.getRandomSalt();
			// 4字节随机码
			StreamUtil.writeInt(fos, randomKey);
			// 授权码
			StreamUtil.writeText(fos, serverInfo.getAuthNum(), randomKey);
			// ip地址
			StreamUtil.writeText(fos, serverInfo.getIpAddr(), randomKey);
			// 4字节端口号
			StreamUtil.writeInt(fos, serverInfo.getPort());
			fos.flush();
			this.path=folder.getAbsolutePath();
			this.message="成功构建授权文件";
			this.success=true;
		}catch(MessageException e){
			this.message=e.getMessage();
		}catch(Throwable e){
			this.message="构建授权文件失败";
			SinotnLogger.DEBUG.error("构建授权文件发生系统错误", e);
		}finally{
			if(fos!=null){
				try{
					fos.close();
				}catch(Throwable e){}
			}
			this.persent=100;
		}
	}
}
